-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
101 lines (89 loc) · 2 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <iostream>
using namespace std;
class CircularQueue {
private:
int *arr;
int front, rear, size;
public:
CircularQueue(int size) {
this->size = size;
arr = new int[size];
front = -1;
rear = -1;
}
~CircularQueue() {
delete[] arr;
}
bool isFull() {
return (front == (rear + 1) % size);
}
bool isEmpty() {
return (front == -1);
}
void enqueue(int value) {
if (isFull()) {
cout << "Queue is full.\n";
return;
}
if (isEmpty()) {
front = 0;
}
rear = (rear + 1) % size;
arr[rear] = value;
cout << "Enqueued: " << value << endl;
}
void dequeue() {
if (isEmpty()) {
cout << "Queue is empty.\n";
return;
}
cout << "Dequeued: " << arr[front] << endl;
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % size;
}
}
void display() {
if (isEmpty()) {
cout << "Queue is empty.\n";
return;
}
cout << "Queue: ";
int i = front;
while (true) {
cout << arr[i] << " ";
if (i == rear) break;
i = (i + 1) % size;
}
cout << endl;
}
};
int main() {
int size, choice, value;
cout << "Enter the size of the queue: ";
cin >> size;
CircularQueue q(size);
while (true) {
cout << "\n1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to enqueue: ";
cin >> value;
q.enqueue(value);
break;
case 2:
q.dequeue();
break;
case 3:
q.display();
break;
case 4:
return 0;
default:
cout << "Invalid choice.\n";
}
}
}